package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.PDetailsRepository;
import com.chz.SupermarketMS.dao.SDetailsRepository;
import com.chz.SupermarketMS.dto.CommodityPD;
import com.chz.SupermarketMS.dto.CommoditySD;
import com.chz.SupermarketMS.entities.Commodity;
import com.chz.SupermarketMS.entities.SDetails;
import com.chz.SupermarketMS.entities.Sale;
import com.chz.SupermarketMS.service.CommodityService;
import com.chz.SupermarketMS.service.SDetailsService;
import com.chz.SupermarketMS.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("sDetails")
public class SDetailsController {

    @Autowired
    SDetailsService sDetailsService;

    @Autowired
    SaleService saleService;

    @Autowired
    CommodityService commodityService;

    @Autowired
    SDetailsRepository sDetailsRepository;


    @GetMapping
    public String displaySDetails(Model model){

        List<SDetails> sDetails = sDetailsService.getAll();
        model.addAttribute("sDetails",sDetails);

        List<CommoditySD> commoditySDS= sDetailsRepository.commoditySD();
        model.addAttribute("commoditySD",commoditySDS);

        return "sDetails/list-sDetails";
    }

    @GetMapping("/new")
    public String displaySDetailsForm(Model model){

        SDetails aSDetails = new SDetails();
        List<Sale> sales=saleService.getAll();
        List<Commodity> commodities = commodityService.getAll();
        model.addAttribute("allCommodities",commodities);
        model.addAttribute("allSale",sales);
        model.addAttribute("sDetails",aSDetails);

        return "sDetails/new-sDetails";
    }

    @PostMapping("/save")
    public String createSDetails(Model model, @RequestParam List<Long> commodities, SDetails sDetails){

        sDetailsService.save(sDetails);

        return "redirect:/sDetails";
    }

    @GetMapping("/update")
    public String displaySDetailsUpdateForm(@RequestParam("id") long theId, Model model) {
        SDetails theSDetails = sDetailsService.findBySpId(theId);
        model.addAttribute("sDetails", theSDetails);
        return "sDetails/new-sDetails";
    }
    @GetMapping("/delete")
    public String deleteSDetails(@RequestParam("id")long theId, Model model) {
        SDetails theSDetails = sDetailsService.findBySpId(theId);
        sDetailsService.delete(theSDetails);
        return "redirect:/sDetails";
    }

}
